package com.lee.transactionaldemo.service.required;

import com.lee.transactionaldemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

/**
 * @author ：liylw
 * @date ：Created in 2021/4/23 9:13
 */
@Service
public class Require1 {

    @Autowired
    private Require2 require2;

    @Autowired
    private UserService userService;


    /**
     * 都插入
     */
    public void testRequired1(){
        userService.saveUserASuccess();
        require2.testWithOutTransFail();
    }


    /**
     * 都没插入
     */
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public void testRequired2(){
        userService.saveUserASuccess();
        require2.testWithOutTransFail();
    }

    /**
     * 都插入
     */
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public void testRequired7(){
        userService.saveUserASuccess();
        try {
            require2.testWithOutTransFail();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * a,b都回滚了， 这个有点反常。
     *  Transaction rolled back because it has been marked as rollback-only
     *  加上这个 TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();  就没有上面的异常了
     */
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public void testRequired8(){
        userService.saveUserASuccess();
        try {
            require2.testFail();
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
    }

    /**
     * A插入   B没插入
     */
    public void testRequired3(){
        userService.saveUserASuccess();
        require2.testFail();
    }


    /**
     * 都没插入
     */
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public void testRequired4(){
        userService.saveUserASuccess();
        require2.testFail();
    }

    /**
     * 都没插入
     */
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public void testRequired5(){
        require2.testWithOutTransSuccess();
        userService.saveUserAFail();

    }

    /**
     * 都没插入
     */
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public void testRequired6(){
        require2.testSuccess();
        userService.saveUserAFail();
    }

}
